package cn.itcast.bos.web.action.base;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard> {
    private Standard standard = new Standard();
    @Override
    public Standard getModel() {
        return standard;
    }

    @Autowired
    private StandardService standardService;

    @Action(value = "standard_save",results = {@Result(name = "success",type ="redirect",location = "./pages/base/standard.html")})
    public String save(){
        standardService.save(standard);
        return SUCCESS;
    }

    @Action(value = "standard_findAll",results = {@Result(name = "findall",type = "json")})
    public String findAll(){
        List<Standard> all = standardService.findAll();
        ActionContext.getContext().getValueStack().push(all);
        /*Standard byId = standardService.findById(1);
        System.out.println(byId+"根据ID查询");
        System.out.println("--------------");
        List<Standard> byName = standardService.findByName("2");
        System.out.println(byName+"根据NAME查询");
        System.out.println("--------------");
        System.out.println(all.toString());*/
        return "findall";
    }

    //属性驱动
    private int page;
    private int rows;

    public void setPage(int page) {
        this.page = page;
    }
    public void setRows(int rows) {
        this.rows = rows;
    }

    @Action(value = "standard_pageQuery",results = {@Result(name = "success",type = "json")})
    public String findByPage(){

        //使用PageRequest对象封装查询数据，并获取查询结果Page<Standard>对象
        Pageable pageBean = new PageRequest(page-1,rows);
        Page<Standard> pageData = standardService.findPageData(pageBean);
        HashMap<String, Object> result = new HashMap<>();
        result.put("total",pageData.getTotalElements());
//        result.put("rows",pageData.getTotalPages());
        result.put("rows",pageData.getContent());
        ActionContext.getContext().getValueStack().push(result);
        System.out.println(result);
        return SUCCESS;
    }






}
